package com.ramos.kuaixiao.shops.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.caller.BankABCCaller;
import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.OrderItemAdapter;
import com.ramos.kuaixiao.entity.OrderDetail;
import com.ramos.kuaixiao.shops.entity.MallOrder;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MallOrderDetailActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "MallOrderDetail";
    private Context mContext;
    private LinearLayout title_reback;
    private TextView title_text;
    private ListView mListView;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    private OrderItemAdapter mAdapter;
    private List<OrderDetail> productList = new ArrayList<>();
    TextView tv_salebillid;
    TextView tv_salebilldate;
    TextView tv_customer;
    TextView tv_selectck;
    TextView tv_shouhuoren;
    TextView tv_shouhuotel;
    TextView tv_shouhuodizhi;
    TextView tv_num;
    TextView tv_pay;
    TextView tv_total;
    LinearLayout ll;
    String orderId;
    String dealerId;
    String mToken;
    String storeHouseId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mall_order_detail);
        mContext = this;
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title_mall), false);
        initView();
    }

    private void initView() {
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("订单详情");
        tv_pay = (TextView) findViewById(R.id.tv_pay);
        tv_pay.setOnClickListener(this);
        tv_total = (TextView) findViewById(R.id.tv_total);
        ll  = (LinearLayout) findViewById(R.id.ll);
        tv_salebillid = (TextView) findViewById(R.id.tv_salebillid);
        tv_salebilldate = (TextView) findViewById(R.id.tv_salebilldate);
        tv_customer = (TextView) findViewById(R.id.tv_customer);
        tv_selectck = (TextView) findViewById(R.id.tv_selectck);
        tv_shouhuoren = (TextView) findViewById(R.id.tv_shouhuoren);
        tv_shouhuotel = (TextView) findViewById(R.id.tv_shouhuotel);
        tv_shouhuodizhi = (TextView) findViewById(R.id.tv_shouhuodizhi);
        tv_num = (TextView) findViewById(R.id.tv_num);
        mListView = (ListView) findViewById(R.id.orderDetailListView);

        MallOrder findOrderDetail = (MallOrder) getIntent().getExtras().get("order");
        if(findOrderDetail != null){
            storeHouseId = findOrderDetail.getStoreHouseId();
            orderId = findOrderDetail.getOrderId();
            dealerId = findOrderDetail.getDealerId();
            mToken = findOrderDetail.getToken();
            Log.d(TAG, "mToken " + mToken + " orderStuts:"+findOrderDetail.getOrderStatus());
            if(StringUtil.isEmpty(mToken)){
                getToken(findOrderDetail.getOrderId());
            }
            if (!StringUtil.isEmpty(findOrderDetail.getDmsOrderId())) {
                tv_salebillid.setText(findOrderDetail.getDmsOrderId());
            } else {
                tv_salebillid.setText(findOrderDetail.getOrderId());
            }

            tv_salebilldate.setText(findOrderDetail.getCustomerName());

            tv_customer.setText(findOrderDetail.getOrderDate());
            tv_selectck.setText(App.df.format(Double.valueOf(findOrderDetail.getOrderTotalPrice())));
            tv_shouhuoren.setText(findOrderDetail.getComunicatePeople());
            tv_shouhuotel.setText(findOrderDetail.getTelephone());
            tv_shouhuodizhi.setText(findOrderDetail.getDstAddr());
            tv_total.setText("总共："+findOrderDetail.getOrderTotalPrice());
            productList = findOrderDetail.getDetailList();
            tv_num.setText(productList.size() + "件");
            if (productList.size() > 0) {
                mAdapter = new OrderItemAdapter(mContext, productList, storeHouseId, false);
                mListView.setAdapter(mAdapter);
                Utils.setListViewHeightBasedOnChildren(mListView);
                //Log.d(TAG, "result " + productList.size());
            } else {
                tv_num.setText("0件");
            }
            if(findOrderDetail.getOrderStatus().equals("KEEP")){
                ll.setVisibility(View.VISIBLE);
            } else {
                ll.setVisibility(View.GONE);
            }
        }
    }

    private void getToken(String orderId) {
        try {
            String url = NetUtils.FIND_TOKEN;
            String path = url + SharedPreference.getPreferString("dealer") + "&orderId="+orderId;
            Log.d(TAG, "path:" + path);
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体

                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result : " + result);
                        org.json.JSONObject user = new org.json.JSONObject(result);
                        if (user.getInt("status") == 200) {
                            mToken = user.getString("data");
                            Log.d(TAG, "result: mToken" + mToken);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {

                }
            });
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
                break;
            case R.id.tv_pay:
                sendOrder();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String param  = intent.getExtras().getString("from_bankabc_param");
        Log.i(TAG, " dealerId : "+dealerId + " orderId:" + orderId + " param = " + param );
        String[] results = param.split("&");
        if (!StringUtil.isEmpty(param)) {
            String [] token =  results[0].split("=");
            if(token.length == 1 || StringUtil.isEmpty(token[1])){
                ToastUtils.show("订单信息还未同步至银行，暂时无法支付，请稍后再试");
            } else {
                String[] status = results[1].split("=");
                if(status.length > 1){
                    if(!StringUtil.isEmpty(status[1])){
                        if(status[1].equals("0000")){
                            Toast.makeText(this, "支付成功", Toast.LENGTH_LONG).show();
                            updatePay("0000");
                            finish();
                        } else if(status[1].equals("9999")){
                            Toast.makeText(this, "支付未成功", Toast.LENGTH_LONG).show();
                        } else if(status[1].equals("PA500401")){
                            Toast.makeText(this, "已存在成功支付的订单", Toast.LENGTH_LONG).show();
                        }else {
                            String[] msg = results[2].split("=");
                            if(msg.length > 1) {
                                //updatePay(msg[1]);
                                Toast.makeText(this, "未成功支付：" + msg[1], Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(this, "未成功支付", Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                }
            }
        }
    }

    private void updatePay(String msg) {
        try {
            String url = NetUtils.UPDATE_PAY_STATUS;
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(30000);
            // 创建请求参数的封装的对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dealerId", dealerId);
            jsonObject.put("orderId", orderId);
            jsonObject.put("orderStatus", msg);
            Log.d(TAG, "updatePay " + url + " "+jsonObject.toString());
            ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            stringEntity.setContentType("application/json");
            // 执行post方法
            client.post(mContext, url, stringEntity, "application/json", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {

                    Log.d(TAG, "updatePay " + responseBody.toString());
                    try {
                        if (responseBody.getInt("status") == 200) {
                            //JSONObject user = responseBody.getJSONObject("data");

                        } else {

                        }
                    } catch (JSONException e) {

                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                    throwable.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void sendOrder() {
        if(StringUtil.isEmpty(mToken)){
            ToastUtils.show("订单信息还未同步至银行，暂时无法支付，请稍后再试");
        } else {
            /**
             * 判断手机上是否具备调起农行掌银的条件
             */
            if (BankABCCaller.isBankABCAvaiable(this)) {
                /**
                 * 调起农行掌银
                 */
                Log.d(TAG, "mToken1 " + mToken);
                BankABCCaller.startBankABC(this, "com.ramos.kuaixiao", "com.ramos.kuaixiao.shops.ui.MallOrderDetailActivity", "pay", mToken);
            } else {//客户手机未安装农行掌银APP的处理逻辑，由第三方APP自行实现
                Toast.makeText(this, "没安装农行掌银，或已安装农行掌银版本不支持", Toast.LENGTH_LONG).show();
            }
        }
    }
}
